﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Casamiel.Domain.Entity;
using Casamiel.Domain;
using Casamiel.Domain.Request;
using Casamiel.Common.Extensions;
using System.Linq;
using System.Globalization;
using Casamiel.Domain.Request.IC;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class TmallCreateOrderCommandHandler : BaseCommandHandler, IRequestHandler<TmallCreateOrderCommand, BaseResult<string>>
	{
		private readonly IMbrStoreRepository _mbrStoreRepository;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="optionsSnapshot"></param>
		/// <param name="mbrStoreRepository"></param>
		public TmallCreateOrderCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> optionsSnapshot,
			IMbrStoreRepository mbrStoreRepository)
	  : base(netICService, httpClientFactory, optionsSnapshot)
		{
			_mbrStoreRepository = mbrStoreRepository;
		}

		public async Task<BaseResult<string>> Handle(TmallCreateOrderCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			if (this.Casasettings.ApiName == "hgspApi") {
				if (request.StoreId == 130) {
					request.OrderType = 1;
				}
			}
			var storeinfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
			if (storeinfo == null) {
				return new BaseResult<string>(null, 9999, "门店信息有误！");
			}
			if (request.TakeTime < DateTime.Now) {
				return new BaseResult<string>(null, -25, "自提时间有误");
			}
			var Orderoriginprice = 0M;
			var queryreq = new Domain.Request.ProductStockQueryReq { shopid = storeinfo.RelationId, product = new List<ProductStockReq>() };
			var icdto = new IcconsumeReq {
				Phoneno = request.ContactPhone,
				Shopid = storeinfo.RelationId,
				Pickuptime = request.TakeTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")),
				Rebate = $"{request.DiscountMoney}".ToDouble(0)
			};
			icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();

			var icpricereq = new Domain.Request.IC.IcPriceReq { Shopid = storeinfo.RelationId, Product = new List<Domain.Request.IC.ProductItemReq>() };


			var BaseGoodsList = new List<CakeGoodsGetBaseRsp>();


			foreach (var item in request.GoodsList) {
				var goodbase = await GetGoodsByIdStoreId(request.StoreId, item.GoodsBaseId).ConfigureAwait(false);
				if (goodbase != null) {
					BaseGoodsList.Add(goodbase);
				}
				//  return new BaseResult<string>(null, -999, $"{item.GoodsBaseId}产品不存在");
				if (goodbase.StockDays > 1) {
					if (request.TakeTime.DayOfYear != DateTime.Now.DayOfYear) {
						if (request.TakeTime < DateTime.Parse(DateTime.Now.AddDays(goodbase.StockDays).ToString("yyyy-MM-dd 00:00:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
							return new BaseResult<string>(null, -28, "本款蛋糕需提前2天预定");
						}
					}
				}
				icpricereq.Product.Add(new Domain.Request.IC.ProductItemReq {
					Pid = $"{goodbase.GoodsRelationId}"
				});
				queryreq.product.Add(new Domain.Request.ProductStockReq { pid = $"{goodbase.GoodsRelationId}", count = item.GoodsQuantity });
			}


			var iprics = await NetICService.Icprice(icpricereq).ConfigureAwait(false);

			if (iprics != null && iprics.product.Count > 0) {
				for (int i = 0; i < BaseGoodsList.Count; i++) {
					var iteminfo = iprics.product.Find(cw => cw.pid == $"{BaseGoodsList[i].GoodsRelationId}");
					if (iteminfo != null) {
						BaseGoodsList[i].Price = iteminfo.icprice;
					} else {
						return new BaseResult<string>(null, 999, $"{ BaseGoodsList[i].Title},{ BaseGoodsList[i].GoodsRelationId},sku不对");
					}
					var goods = request.GoodsList.FirstOrDefault(c => c.GoodsBaseId == BaseGoodsList[i].GoodsBaseId);
					Orderoriginprice += BaseGoodsList[i].Price * goods.GoodsQuantity;
					icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = iteminfo.pid, Count = goods.GoodsQuantity });
				}

				//foreach (var item in BaseGoodsList)
				//{
				//    var iteminfo = iprics.product.Find(cw => cw.pid == item.GoodsRelationId.ToString());
				//    if (iteminfo != null)
				//    {
				//        item.Price = iteminfo.icprice;
				//    }
				//    else
				//    {
				//        return new BaseResult<string>(null, 999, $"{item.Title},{item.GoodsRelationId},sku不对");
				//    }
				//   var goods=  request.GoodsList.Where(c => c.GoodsBaseId == item.GoodsBaseId).FirstOrDefault();
				//    Orderoriginprice += item.Price * goods.GoodsQuantity ;
				//    icdto.product.Add(new IcconsumeReq.IcconsumeProductItem { pid = iteminfo.pid, count = goods.GoodsQuantity });
				//}
			} else {
				return new BaseResult<string>(null, -22, "产品已经下架");
			}

			if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
				return new BaseResult<string>(null, -23, "抱歉该自提时间不能预定");
			}
			if (storeinfo.IsLimitStock == 0) {
				if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && request.TakeTime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear) {
					return new BaseResult<string>(null, -23, "抱歉该时间段不能预定次日蛋糕");
				}
			}
			if (request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
				var zmodle = await NetICService.Productstockquery(queryreq).ConfigureAwait(false);
				if (zmodle != null && zmodle.product.Count > 0) {
					for (int i = 0; i < BaseGoodsList.Count; i++) {
						var info = request.GoodsList.SingleOrDefault(c => c.GoodsBaseId == BaseGoodsList[i].GoodsBaseId);
						var iteminfo = zmodle.product.Find(cw => cw.pid == $"{BaseGoodsList[i].GoodsRelationId}");
						if (iteminfo != null) {
							BaseGoodsList[i].Price = iteminfo.icprice;
						} else {
							return new BaseResult<string>(null, 999, $"{ BaseGoodsList[i].Title},{ BaseGoodsList[i].GoodsRelationId},sku不对");
						}

						if (request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
							if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
								return new BaseResult<string>(null, -23, "抱歉该时间段不能预定当天蛋糕自提");
							}
							if (storeinfo.IsLimitStock == 0) {
								if (iteminfo.count < info.GoodsQuantity) {
									return new BaseResult<string>(null, -21, $"{ BaseGoodsList[i].Title},库存不足");
								}
							}

						}

						// icdto.product.Add(new IcconsumeReq.IcconsumeProductItem { pid = iteminfo.pid, count = info.GoodsQuantity });
					}

				} else {
					return new BaseResult<string>(null, -22, "产品已经下架");
				}
			}
			//else
			//{
			//    var iprics = await _icApiService.icprice(dto);
			//    if (iprics != null && iprics.product.Count > 0)
			//    {
			//        foreach (var item in data.GoodsList)
			//        {
			//            var iteminfo = iprics.product.Find(cw => cw.pid == item.RelationId.ToString());
			//            if (iteminfo != null)
			//            {
			//                item.Price = iteminfo.icprice;
			//            }
			//            else
			//            {
			//                return new BaseResult<string>(null, 999, $"{item.Title},{item.RelationId},sku不对");
			//            }
			//            Orderoriginprice += item.Price * item.GoodsQuantity;
			//            icdto.product.Add(new IcconsumeReq.IcconsumeProductItem { pid = iteminfo.pid, count = item.GoodsQuantity });
			//        }
			//    }
			//    else
			//    {
			//        return new BaseResult<string>(null, -22,"产品已经下架" );
			//    }
			//}
			//_netICService.productstockquery(new Domain.Request.ProductStockQueryReq
			if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US")) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
				return new BaseResult<string>(null, -23, "抱歉该自提时间不能预定");
			}

			var icentity = await NetICService.Thirdorder(icdto).ConfigureAwait(false);
			OrderLogger.Trace($"thirdorder,req:{JsonConvert.SerializeObject(icdto)},result:{JsonConvert.SerializeObject(icentity)}");
			if (icentity.code == 0) {
				var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
				request.IcTradeNO = jobject["tradeno"].ToString();
				request.BillNo = jobject["billno"].ToString();
			} else {
				return new BaseResult<string>(null, icentity.code, icentity.msg);
			}
			//data.IcTradeNO = ictradeNO;
			//data.BillNo = billNO;
			var url = "TPP/v3/Order/AddTMall";
			try {

				var result1 = await PostAsync(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);//.AddTmallOrder(data);
				var Jorder = JsonConvert.DeserializeObject<JObject>(result1);
				if (Jorder["resultNo"].ToString() == "00000000") {
					var model = new { code = 0, msg = "" };
					// var entity = await _storeService.GetByOrderCodeAsync<ICasaMielSession>(data.OrderCode);
					var pay = new IcConsumepayReq {
						Phoneno = request.ContactPhone,
						Createinvoice = true,
						Shopid = storeinfo.RelationId,
						Tradeno = request.IcTradeNO
					};
					pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
					{
						new IcConsumepayReq.PaycontentItem
						{
							Paytype = "7",
							Paymoney = (Orderoriginprice - request.DiscountMoney + request.FreightMoney).ToString(CultureInfo.CreateSpecificCulture("en-US")).ToDouble(0),
							Paytradeno = request.OrderCode
						}
					};
					if (request.FreightMoney > 0) {
						pay.Payfee = new List<IcConsumepayReq.PayfeeItem>{new IcConsumepayReq.PayfeeItem
						{
							Fee = request.FreightMoney.ToString(CultureInfo.CreateSpecificCulture("en-US")).ToDouble(0),
							Feetype="1",
							Description = "配送费"
						}};
					}
					var zmodel = await NetICService.Icconsumepay(pay).ConfigureAwait(false);

					OrderLogger.Trace($"icconsumepay,req:{JsonConvert.SerializeObject(pay)},result:{JsonConvert.SerializeObject(zmodel)}");
					if (zmodel.code == 0) {
						var result = await CakeOrderChangeStatus(request.OrderCode, request.ContactPhone, 1, 3, "").ConfigureAwait(false);
						//using (var uow = _session.UnitOfWork(IsolationLevel.Serializable))
						//{
						//    var noticEntity = new Notice_baseEntity()
						//    {
						//        RemindTime = DateTime.Now.AddMinutes(-3),
						//        CreateTime = DateTime.Now,
						//        RelationId = entity.OrderBaseId,
						//        StoreId = entity.StoreId,
						//        NoticeType = 0
						//    };
						//    await _storeService.AddNoticeAsync(noticEntity, uow);
						//}
						return new BaseResult<string>("", 0, "下单成功");
					} else if (zmodel.code == 202) {
						pay = new IcConsumepayReq {
							Phoneno = request.ContactPhone,
							Shopid = storeinfo.RelationId,
							Tradeno = request.IcTradeNO,
							Createinvoice = true
						};
						pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
						{
							new IcConsumepayReq.PaycontentItem
							{
								Paytype = "7",
								Paymoney = (Orderoriginprice - request.DiscountMoney).ToString(CultureInfo.CreateSpecificCulture("en-US")).ToDouble(0),
								Paytradeno = request.OrderCode + "@" + DateTime.Now.ToString("ffff",CultureInfo.CreateSpecificCulture("en-US"))
							}
						};
						zmodel = await NetICService.Icconsumepay(pay).ConfigureAwait(false);
						OrderLogger.Trace($"icconsumepay,req:{JsonConvert.SerializeObject(pay)},result:{JsonConvert.SerializeObject(zmodel)}");
						if (zmodel.code == 0) {
							var result = await CakeOrderChangeStatus(request.OrderCode, request.ContactPhone, 1, 3, "").ConfigureAwait(false);
							//using (var uow = _session.UnitOfWork(IsolationLevel.Serializable))
							//{
							//    var noticEntity = new Notice_baseEntity()
							//    {
							//        RemindTime = DateTime.Now.AddMinutes(-3),
							//        CreateTime = DateTime.Now,
							//        RelationId = entity.OrderBaseId,
							//        StoreId = entity.StoreId,
							//        NoticeType = 0
							//    };
							//    await _storeService.AddNoticeAsync(noticEntity, uow);
							//}
							return new BaseResult<string>("", 0, "下单成功");
						}
					}
					return new BaseResult<string>("", zmodel.code, zmodel.msg);
				} else {
					var req = new ThirdOrderBackReq { Tradeno = request.IcTradeNO };
					var d = await NetICService.Thirdorderback(req).ConfigureAwait(false);
					//orderlogger.Trace($"icconsumeback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
					return new BaseResult<string>("", 9999, Jorder["resultRemark"].ToString());
				}
			} catch (System.Net.Sockets.SocketException ex) {
				var req = new ThirdOrderBackReq { Tradeno = request.IcTradeNO };
				var d = await NetICService.Thirdorderback(req).ConfigureAwait(false);
				OrderLogger.Trace($"icconsumeback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
				OrderLogger.Error($"AddTmallOrder:{JsonConvert.SerializeObject(d)}");
				return new BaseResult<string>("", 9999, ex.Message);
			}
		}


	}
}
